/*!
 * Page: mine/currency/Currency
 * License: MIT
 * Created: 2019-10-10 11:38
 */
import { taskApi } from '/api/task'
import { currencyApi } from '/api/currency'
import { getServer, isLogin } from '/store/mutations'
import { checkAuth, getDomoUser, getNotifications } from '/store/actions'
import { GlobalData } from '/store/state'
import { $event } from '/utils'
import { userApi } from '/api/user'
import { mallApi } from '/api/mall'
Page({
  data: {
    currentIndex: 0,
    tabs: [
      {
        title: `${GlobalData.currencyName}攻略`,
        index: 0,
      },
      {
        title: '兑换',
        index: 1,
      },
      {
        title: '获取明细',
        index: 2,
      },
      {
        title: '消耗明细',
        index: 3,
      },
    ],
    user: {} as any,
    limit: 15,
    loading: false,
    tasks: [] as any[],
    topicTasks: [] as any[],
    currencyName: GlobalData.currencyName,
    /** 积分兑换 */
    data_1: {
      canLoad: true,
      data: [],
    },
    // 收入
    data_2: {
      canLoad: true,
      data: [],
    },
    // 支出
    data_3: {
      canLoad: true,
      data: [],
    },
    scrollClass: false,
    data_1_loaded: false,
    data_2_loaded: false,
    navigationHeight: GlobalData.navigationHeight,
    assess: GlobalData.access,
    token: false,
    invite: GlobalData.invite,
    invitee: {},
    show: false,
    showIndex: 0,
    signInData: {} as any,
    isSignIn: {},
    //  tabbar 小红点检查，第一次加载页面时需要获取
    hadGetNewMsg: false,
  },
  async onLoad() {
    $event.on('after:login', this, async () => {
      if (this.data.tasks.length === 0) {
        await this.getUserInfo()
        await this.fetchTasks()
        const token = wx.getStorageSync(`${getServer()}/accessToken`).data
        this.setData({
          token: token,
        })
      }
    })
    this.setData({
      access: GlobalData.access,
      currencyName: GlobalData.currencyName,
      navigationHeight: GlobalData.navigationHeight,
      [`tabs[0].title`]: `${GlobalData.currencyName}攻略`,
      invite: GlobalData.invite,
      exchangeRate: GlobalData.currency.settings['recharge-ratio'],
    })
    $event.on('after:boot', this, () => {
      this.setData({
        access: GlobalData.access,
        currencyName: GlobalData.currencyName,
        navigationHeight: GlobalData.navigationHeight,
        [`tabs[0].title`]: `${GlobalData.currencyName}攻略`,
        invite: GlobalData.invite,
        exchangeRate: GlobalData.currency.settings['recharge-ratio'],
      })
    })
    const token = wx.getStorageSync(`${getServer()}/accessToken`).data
    this.setData({
      token: token,
    })
    $event.on('message:showMessageDot', this, (isShow) => {
      if (typeof this.getTabBar === 'function' && this.getTabBar()) {
        this.setData({
          hadGetNewMsg: true,
        })
        this.getTabBar().setData({
          showMeesageDot: isShow,
        })
      }
    })
    $event.on('message:showMineDot', this, (isShow) => {
      if (typeof this.getTabBar === 'function' && this.getTabBar()) {
        this.getTabBar().setData({
          showMineDot: isShow,
        })
      }
    })
  },
  async onShow() {
    // 自定义tab
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 2,
      })
    }
    if (isLogin()) {
      await getDomoUser()
      this.getUserInfo()
      this.fetchTasks()
      if (!this.data.hadGetNewMsg) {
        getNotifications()
      }
    } else {
      checkAuth()
    }
  },
  /**
   * 获取用户信息及用户圈子
   */
  async getUserInfo() {
    const user = wx.getStorageSync(`${getServer()}/logged`).data || {}
    const invitee = await userApi.getInvitee({ offset: 0, limit: 20 })
    this.getSignData()
    this.setData({
      user,
      invitee,
    })
  },
  changeIndex(e: any) {
    const {
      currentTarget: {
        dataset: { index },
      },
    } = e
    this.setData(
      {
        currentIndex: index,
      },
      () => {
        if (+index === 1 || +index === 2 || +index === 3) {
          // @ts-ignore
          const loaded: boolean = this.data[`data_${index}_loaded`]
          if (!loaded) {
            ; +index === 1 ? this.getProduct() : this.fetchData()
          }
        }
      },
    )
  },
  /** 获取签到数据 */
  async getSignData() {
    const signInData = await userApi.getSignInList()
    const isSignIn = await userApi.isSignIn()
    this.setData({
      signInData,
      isSignIn,
    })
  },
  resolveTask(task: any) {
    switch (task.type) {
      case 'task:login':
        task.name = '登录'
        task.icon = 'ico_catcoin_login@2x.png'
        break
      case 'task:comments':
        task.name = '评论(≥8字)'
        task.icon = 'ico_catcoin_comment@2x.png'
        task.warn = true
        break
      case 'task:shares':
        task.name = '分享到微信'
        task.icon = 'ico_catcoin_share@2x.png'
        break
      case 'task:likes':
        task.name = '不同内容点赞'
        task.icon = 'ico_catcoin_zan@2x.png'
        break
      case 'task:follow-topic':
        task.name = '关注圈子'
        task.icon = 'ico_catcoin_ximao@2x.png'
        break
      case 'task:theme-discuss':
        task.name = '不同话题讨论'
        task.icon = 'ico_catcoin_topic@2x.png'
        break
      case 'task:commodity-comments':
        task.name = '商品点评'
        task.icon = 'ico_catcoin_goods@2x.png'
        break
      case 'task:knowledge-comments':
        task.name = '知识点评'
        task.icon = 'ico_catcoin_knowledge.png'
        break
      case 'task:be-liked':
        task.name = '被点赞'
        task.icon = 'ico_catcoin_zan@2x.png'
    }

    return task
  },
  /** 获取任务状态 */
  async fetchTasks() {
    const taskSource = await taskApi.getTasks()
    const newTask = taskSource.map((task) => {
      return this.resolveTask(task)
    })

    const tasks = taskSource.filter((t) => t.type !== 'task:be-liked')
    const topicTasks = newTask.filter((t) => t.type === 'task:be-liked')
    this.setData({ tasks, topicTasks })
  },
  onPullDownRefresh() {
    const {
      data: { currentIndex },
    } = this
    if ([2, 3].includes(currentIndex)) {
      this.fetchData(false)
    }
    if ([1].includes(currentIndex)) {
      this.getProduct(false)
    }
  },
  loadMore() {
    const {
      data: { currentIndex },
    } = this
    if ([2, 3].includes(currentIndex)) {
      this.fetchData(true)
    }
    if ([1].includes(currentIndex)) {
      this.getProduct(true)
    }
  },
  /** 获取积分商品 */
  getProduct(loadmore = false) {
    const {
      data: { currentIndex, loading, limit },
    } = this
    if (loading) return
    // @ts-ignore
    const {
      data: {
        // @ts-ignore
        [`data_${currentIndex}`]: { canLoad, data },
      },
    } = this
    if (!canLoad) return
    this.setData({ loading: true })
    const offset = loadmore ? data.length : 0
    mallApi
      .getCommodities({
        order: 'topped_at desc, updated_at desc',
        limit,
        type: 'score',
        offset,
      })
      .then((data) => {
        this.setData({
          loading: false,
          [`data_${currentIndex}_loaded`]: true,
          [`data_${currentIndex}`]: {
            // @ts-ignore
            data: loadmore ? [...this.data[`data_${currentIndex}`].data, ...data] : data,
            canLoad: data.length == limit,
          },
        })
      })
      .catch(() => {
        this.setData({
          loading: false,
        })
      })
  },
  /** 收入流水 */
  async fetchData(loadmore = false) {
    const {
      data: { currentIndex, loading, limit },
    } = this
    if (loading) return
    const type = currentIndex === 2 ? 1 : -1
    // @ts-ignore
    const {
      data: {
        // @ts-ignore
        [`data_${currentIndex}`]: { canLoad, data },
      },
    } = this
    if (!canLoad) return
    this.setData({ loading: true })
    const after = loadmore && data[data.length - 1] ? data[data.length - 1].id : 0
    currencyApi
      .currencyOrder({ after, type })
      .then((data) => {
        this.setData({
          loading: false,
          [`data_${currentIndex}_loaded`]: true,
          [`data_${currentIndex}`]: {
            // @ts-ignore
            data: loadmore ? [...this.data[`data_${currentIndex}`].data, ...data] : data,
            canLoad: data.length === limit,
          },
        })
      })
      .catch(() => {
        this.setData({
          loading: false,
        })
      })
  },
  /** 复制邀请码 */
  copyInviteCode: (e: any) => {
    const {
      currentTarget: {
        dataset: { invitecode },
      },
    } = e
    wx.setClipboardData({
      data: invitecode,
      success: () => {
        wx.getClipboardData({
          success: (res) => {
            if (res.data === invitecode)
              wx.showToast({
                title: '复制成功',
              })
          },
        })
      },
    })
  },
  async login() {
    await checkAuth()
  },
  detail(e: WechatMiniprogram.BaseEvent) {
    const showIndex = +e.currentTarget.dataset.id
    this.setData({
      showIndex,
      show: true,
    })
  },
  close() {
    this.setData({
      show: false,
    })
  },
  // 签到
  async signIn() {
    const { day, get_integral } = await userApi.addSignIn()
    if (get_integral) {
      $event.emit('showMessage', {
        message: `连续签到${day}天`,
        amount: get_integral,
      } as GetRewardMessageReturns)
    }
    await getDomoUser()
    this.getUserInfo()
    this.fetchTasks()

  },
  //跳转邀请
  toInvite() {
    wx.navigateTo({
      url: `/mine/invite/invite`,
    })
  },
  //跳转充值
  recharge() {
    wx.navigateTo({
      url: '/pages/recharge/recharge',
    })
  },
  //跳转详细邀请成员
  toinvitee() {
    wx.navigateTo({
      url: `/mine/follow/follow?type=invitee`,
    })
  },
  onHide() { },
})
